/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2022-03-10     xu       the first version
 */
#include <rtthread.h>
#include <stdlib.h>
#include <fal.h>
#include <spi_flash_sfud.h>
#include "n32g45x.h"
#include "drv_gpio.h"
#include "drv_spi.h"

#define W25Q_SPI_CS_PORT         GPIOB
#define W25Q_SPI_CS_PIN          GPIO_PIN_5
#define W25Q_SPI_BUS_NAME        "spi1"
#define W25Q_SPI_DEVICE_NAME     "spi10"
#define W25Q_SPI_FLASH_DEV_NAME  FAL_USING_NOR_FLASH_DEV_NAME

static int w15q_attach()
{
    rt_err_t err = rt_hw_spi_device_attach(W25Q_SPI_BUS_NAME, W25Q_SPI_DEVICE_NAME, W25Q_SPI_CS_PORT, W25Q_SPI_CS_PIN);
    if (err != RT_EOK) {
        rt_kprintf("Attach W25Q device(%s) FAIL!\n", W25Q_SPI_DEVICE_NAME);
        return 1;
    }
    rt_kprintf("Attach W25Q device(%s) OK!\n", W25Q_SPI_DEVICE_NAME);
    return 0;
}

static int w25q_init()
{
    w15q_attach(); // before flash device probe

    if (RT_NULL == rt_sfud_flash_probe(W25Q_SPI_FLASH_DEV_NAME, W25Q_SPI_DEVICE_NAME))
    {
        rt_kprintf("Probe %s FAIL!\n", W25Q_SPI_FLASH_DEV_NAME);
        return 1;
    }

    fal_init(); // after flash device probe
    return 0;
}
INIT_ENV_EXPORT(w25q_init);
// MSH_CMD_EXPORT(w25q_init, W25Q and FAL initialize);

static int w25q_cs(int argc, char* argv[])
{
    int value = 0;
    if (argc <= 1) {
        rt_kprintf("usage: %s [0|1]\n", __func__);
        return -1;
    }

    value = atoi(argv[1]);
    if (value) {
        GPIO_SetBits(W25Q_SPI_CS_PORT, W25Q_SPI_CS_PIN);
    } else {
        GPIO_ResetBits(W25Q_SPI_CS_PORT, W25Q_SPI_CS_PIN);
    }
    return 0;
}
MSH_CMD_EXPORT(w25q_cs, "W25Q CS test");


